package com.beone.admin.security.handler;

import com.beone.admin.security.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Title
 * @Author zero on 2018/4/8.
 * @Copyright © 长沙科权
 */
public class AdminLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
        implements LogoutSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(AdminLogoutSuccessHandler.class);

    private UserCache userCache;

    public void setUserCache(UserCache userCache) {
        this.userCache = userCache;
    }
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , Authentication authentication) throws IOException, ServletException {
        if(authentication == null){
            return;
        }

        SysUser sysUser = (SysUser) authentication.getPrincipal();
        if(sysUser != null){ //移除注销用户的用户缓存信息
            userCache.removeUserFromCache(sysUser.getUsername());

            if(logger.isDebugEnabled()){
                logger.debug("用户{}注销成功。。。。。", sysUser.getUsername());
            }
        }
        super.handle(httpServletRequest, httpServletResponse, authentication);
    }
}
